﻿using System;
using Medianamik.Core.Urls;
using Medianamik.Core;
using Medianamik.UI.Controls;

namespace Medianamik.UI.ConfigManagement
{
    public partial class UrlDictionaryList : BasePage
    {
        protected string UrlFilter
        {
            get
            {
                return ViewState["UrlFilter"] as string ?? string.Empty;
            }
            private set
            {
                ViewState["UrlFilter"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ddlDomains.DataSource = new ObjectFactory<IUrlDictionary>().Get().GetDomains();
                ddlDomains.DataBind();
                GridUrls.DataBind();
            }
        }

        protected void ddlDomains_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridUrls.Rebind();
        }

        protected void GridUrls_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            var domain = ddlDomains.SelectedValue ;
            var urlDictionary = new ObjectFactory<IUrlDictionary>().Get();
            var datasource = urlDictionary.GetEntries(CurrentEditionCulture, domain, UrlFilter);

            ((Telerik.Web.UI.RadGrid)source).DataSource = datasource;
        }

        protected void GridUrls_PageIndexChanged(object source, Telerik.Web.UI.GridPageChangedEventArgs e)
        {
            GridUrls.Rebind();
        }

        protected void UrlFilter_Filter(object sender, GridColumnFilterEventArgs args)
        {
            UrlFilter = args.Value;
            GridUrls.Rebind();
        }
               
        protected override void OnCultureChanged(CultureChangedEventArgs e)
        {
            base.OnCultureChanged(e);
            GridUrls.Rebind();
        }

        protected string FormatUrlForDisplay(Uri pUrl)
        {
            var urlStr = pUrl.PathAndQuery;
            if(urlStr.Length >= 50)
            {
               urlStr = "..." + urlStr.Substring(urlStr.Length - 50);
            }
            return urlStr;
        }
    }
}